var BMapLib = window.BMapLib = BMapLib || {};

(function () {
    /**
     * 声明baidu包
     */
    var baidu = baidu || { guid: "$BAIDU$" };
    (function () {

        baidu.extend = function (target, source) {
            for (var p in source) {
                if (source.hasOwnProperty(p)) {
                    target[p] = source[p];
                }
            }
            return target;
        };
    })();

    var CustomOverlay = BMapLib.CustomOverlay = function (map, opts, content) {
        if (!map) {
            return;
        }
        this._map = map;
        opts = opts || {};
        this._opts = baidu.extend(
            baidu.extend(this._opts || {}, {
                width: 50,
                height: 50,
                close: false,
                offset: {
                    x: 0,
                    y: 0
                },
                click: () => { }
            })
            , opts);

        this._content = content || 'KMap';
    }

    CustomOverlay.prototype = new BMap.Overlay();

    CustomOverlay.prototype.initialize = function () {
        var div = this._div = document.createElement("div");
        div.id = "CustomOverlay-" + (Math.random().toString()).substring(2)
        div.style.position = "absolute";
        div.style.zIndex = BMap.Overlay.getZIndex(this._opts.point.lat);
        div.style.height = this._opts.height + "px";
        div.style.width = this._opts.width + "px";

        if (this._opts.close === true) {
            var close = document.createElement("div");
            close.innerHTML = '<span>x</span>';
            div.appendChild(close);
        }

        var content = document.createElement("div");
        div.appendChild(content);
        content.innerHTML = this._content;
        this._map.getPanes().markerPane.appendChild(div);
        return div;
    }

    CustomOverlay.prototype.draw = function () {
        var pixel = this._map.pointToOverlayPixel(this._opts.point);
        this._div.style.left = pixel.x - this._opts.width / 2 + this._opts.offset.x + 'px';
        this._div.style.top = pixel.y - this._opts.height / 2 + this._opts.offset.y + "px";
    };

    CustomOverlay.prototype.addEventListener = function (event, fun) {
        this._div['on' + event] = fun;
    }

    CustomOverlay.prototype.show = function () {
        if (this._div) {
            this._div.style.display = "";
        }
    }
    CustomOverlay.prototype.hide = function () {
        if (this._div) {
            this._div.style.display = "none";
        }
    }

})();
